<?php

namespace App\Http\Controllers\Client\Talent;

use App\Http\Controllers\ClientController;
use App\Models\Common\File;
use App\Models\Talent;
use App\Models\Tools\Data;
use EasyWeChat\Kernel\Http\StreamResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class TalentApplyController extends ClientController
{
    /**
     * 申请达人认证
     */
    public function index()
    {
        $all = $this->all;
        /**
         * 验证参数
         */
        try {
            if (!isset($all['account_name'])) {
                throw new \Exception('缺少参数:account_name');
            }
            if (!isset($all['channel_id'])) {
                throw new \Exception('缺少参数:channel_id');
            }
            if (!isset($all['apply'])) {
                throw new \Exception('缺少参数:apply');
            }
            if (!isset($all['address'])) {
                throw new \Exception('缺少参数：address');
            }
            if(!is_array($all['address']) || count($all['address']) !== 3){
                throw new \Exception('参数格式错误：address');
            }
            if ($all['apply'] === true && !isset($all['verify_img'])) {
                throw new \Exception('缺少参数:verify_img');
            }
        }catch (\Exception $e) {
            Log::error(TalentApplyController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '缺少参数');
        }
        $account_name = $all['account_name'];
        $channel_id = $all['channel_id'];
        $address = $all['address'];
        $verify_img = null;
        $collection_qr_code = null;

        /**
         * 图片上传
         */
        try {
            // 保存图片
            if (isset($all['verify_img'])) {
                $file_path = 'images/talent/' . $this->we_id;
                $verify_img = File::saveMedia($all['verify_img'], $file_path);
            }
            if (isset($all['collection_qr_code'])) {
                $file_path = 'images/talent/' . $this->we_id;
                $collection_qr_code = File::saveMedia($all['collection_qr_code'], $file_path);
            }
        } catch (\Exception $e){
            Log::error(TalentApplyController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            if($e->getMessage() === '读取上传图片失败'){
                return $this->setReturnJson(-1,'pc端无法上传图片');
            }
            return $this->setReturnJson(-1, '图片上传失败，请联系人工客服处理');
        }

        /**
         * 新建/修改达人信息
         */
        try {
            DB::beginTransaction();
            $talent = DB::table('talent')->where('we_id','=',$this->we_id)->lockForUpdate()->first();
            $talent = json_decode(json_encode($talent), true);
            // 验证重名
            $count = DB::table('talent')
                ->where('we_id','<>',$this->we_id)
                ->where('account_name','=',$account_name)
                ->where('status','=',1)
                ->count();
            if($count){
                DB::rollBack();
                return $this->setReturnJson(-1,'此用户名已被其他账户认证，如有疑问请联系人工客服');
            }
            if($talent){ // 如果当前账号有达人信息，修改此条信息
                $update_msg = ['status' => 0, 'apply_time' => date('Y-m-d H:i:s'),];
                if($channel_id !== $talent['channel_id']){ // channel_id
                    $update_msg['channel_id'] = $channel_id;
                }
                if($account_name !== $talent['account_name']){ // 用户名
                    $update_msg['account_name'] = $account_name;
                }
                if (!is_null($verify_img)) { // 认证图片
                    $update_msg['verify_img'] = $verify_img;
                }
                if (!is_null($collection_qr_code)) { // 收款码
                    $update_msg['collection_qr_code'] = $collection_qr_code;
                }
                if ($address[0] !== $talent['province'] || $address[1] !== $talent['city'] || $address[2] !== $talent['district']){
                    $update_msg['province'] = $address[0];
                    $update_msg['city'] = $address[1];
                    $update_msg['district'] = $address[2];
                }
                if(count($update_msg) === 2){ // 如果没有修改提前结束
                    DB::rollBack();
                    return $this->setReturnJson(0,'您未修改任何账号信息');
                }
                DB::table('talent')
                    ->where('talent_id', '=', $talent['talent_id'])
                    ->update($update_msg);
                // 记录操作日志
                DB::table('talent_log')->insert([
                    'talent_id' => $talent['talent_id'],
                    'active_type' => Data::DATA_DB_TALENT_ACTION_RESUBMIT,//操作：申请
                    'we_id'=>$this->we_id,
                ]);
            } else { // 新建达人信息
                $talent_id = DB::table('talent')
                    ->insertGetId([
                        'we_id'=>$this->we_id,
                        'channel_id'=>$channel_id,
                        'account_name'=>$account_name,
                        'verify_img'=>$verify_img,
                        'collection_qr_code'=>$collection_qr_code,
                        'province'=>$address[0],
                        'city'=>$address[1],
                        'district'=>$address[2],
                        'apply_time'=>date('Y-m-d H:i:s'),
                    ]);
                // 记录操作日志
                DB::table('talent_log')->insert([
                    'talent_id'=>$talent_id,
                    'active_type'=>Data::DATA_DB_TALENT_ACTION_SUBMIT,
                    'we_id'=>$this->we_id,
                ]);
            }
            DB::commit();
            return $this->setReturnJson(0, '达人认证提交成功，我们会在3个工作日内对您提交的资料进行审核');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(TalentApplyController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '账号信息绑定失败，请联系人工客服');
        }

    }

}
